<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from '../../mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object,
      required: true
    },
    colors: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions({ expectedData, actualData, title, name, colors } = {}) {
      console.log(colors,'colors');
      var option = {
        color: colors,
        title: {
          text: title
        },
        tooltip: {
          trigger: 'axis'
        },
        dataZoom: [
          {
            orient: "horizontal",
            show: false,//控制滚动条显示隐藏
            realtime: true, //拖动滚动条时是否动态的更新图表数据
            height: 15, //滚动条高度
            start: 0, //滚动条开始位置（共100等份）
            end: 80,//滚动条结束位置
            bottom: "4%",
            zoomLock: true, //控制面板是否进行缩放
          },
          {
            type: 'inside',
            brushSelect: true,
            start: 0,
            end: 100,
            xAxisIndex: [0],
          }

        ],
        legend: {
          show: true,
          data: [name]
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: actualData
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 100,
          axisLabel: {
            formatter: '{value} %'
          }
        },
        series: [
          {
            name: name,
            type: 'line',
            data: expectedData,
            areaStyle: {
              // normal: {
              //   color: colors,
              //   lineStyle: {
              //     color: colors,
              //     width: 2
              //   }
              // }
            }
          }
        ]
      };
      this.chart.setOption(option)
    }
  }
}
</script>
